package com.imb.common.web.thread;

import com.imb.common.core.enums.ThreadKeyEnum;
import com.imb.common.web.redis.RedisCache;
import com.imb.common.web.thread.ThreadFactorys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class ShutdownManager {

    @Resource
    private RedisCache redisCache;
    @Resource
    private Environment environment;

    @Resource
    private ThreadFactorys threadFactorys;

    private static String threadKey="thread-key";

    @PreDestroy
    public void destroy() {
        shutdownAsyncManager();
    }

    /**
     * 停止异步执行任务
     */
    private void shutdownAsyncManager() {
        try {
            log.info("====关闭后台任务线程池====");
            Map<String,ExecutorService> services= ThreadFactorys.getManagedExecutors();
            for (Map.Entry<String, ExecutorService> stringExecutorServiceEntry : services.entrySet()) {
               log.info("销毁线程池[{}]->{}",stringExecutorServiceEntry.getKey(),stringExecutorServiceEntry.getValue().getClass());
               shutdownAndAwaitTermination(stringExecutorServiceEntry.getValue());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 停止异步执行任务
     */
    private void shutdownAsyncManager2() {
        try {
            log.info("====关闭后台任务线程池====");
            String property = environment.getProperty("server.name");
            String threadName=property+"-thread";
            ExecutorService services=threadFactorys.getManagedExecutors(threadName);
            if(services!=null) {
                log.info("销毁线程池[{}]->{}", threadName, services.getClass());
                shutdownAndAwaitTermination(services);
                Set<Object> cacheSet = redisCache.getCacheSet(ThreadKeyEnum.THREAD_GLOBAL_KEY.getKey());
                log.info(String.valueOf(cacheSet));
                cacheSet.remove(threadName);
                log.info(String.valueOf(cacheSet));
                redisCache.setCacheSet(ThreadKeyEnum.THREAD_GLOBAL_KEY.getKey(), cacheSet);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 停止线程池
     * 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.
     * 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.
     * 如果仍人超時，則強制退出.
     * 另对在shutdown时线程本身被调用中断做了处理.
     */
    public static void shutdownAndAwaitTermination(ExecutorService pool)
    {
        if (pool != null && !pool.isShutdown())
        {
            pool.shutdown();
            try
            {
                if (!pool.awaitTermination(10, TimeUnit.SECONDS))
                {
                    pool.shutdownNow();
                    if (!pool.awaitTermination(10, TimeUnit.SECONDS))
                    {
                        log.info("Pool did not terminate");
                    }
                }
            }
            catch (InterruptedException ie)
            {
                pool.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }
}
